package com.wanchuang.hepos.ui.page.main;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.google.protobuf.InvalidProtocolBufferException;
import com.luck.picture.lib.tools.StringUtils;
import com.wanchuang.hepos.R;
import com.wanchuang.hepos.bridge.data.repository.Apis;
import com.wanchuang.hepos.bridge.data.repository.WebApis;
import com.wanchuang.hepos.bridge.request.HomeRequestViewModel;
import com.wanchuang.hepos.bridge.state.main.HomeFragmentViewModel;
import com.wanchuang.hepos.databinding.FragmentHomeBinding;
import com.wanchuang.hepos.net.NetworkManager;
import com.wanchuang.hepos.net.interfaces.OnRequestCallBack;
import com.wanchuang.hepos.proto.MemberOuterClass;
import com.wanchuang.hepos.proto.Settle;
import com.wanchuang.hepos.ui.base.BaseFragment;
import com.wanchuang.hepos.ui.web.ui.WebViewActivity;
import com.wanchuang.hepos.ui.zxing.activity.CaptureActivity;
import com.wanchuang.hepos.ui.zxing.activity.CaptureBankActivity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件名 : HomeRootFragment
 * 创建者 : MangoWang
 * 创建日期 : 2019/12/24 16:20
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.coml
 * 描述 : TODO
 */
public class HomeFragment extends BaseFragment {
    private FragmentHomeBinding mBinding;
    private HomeFragmentViewModel mViewModel;
    private HomeRequestViewModel mRequestViewModel;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(HomeFragmentViewModel.class);
        mRequestViewModel = ViewModelProviders.of(this).get(HomeRequestViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        mBinding = FragmentHomeBinding.bind(view);
        mBinding.setClick(new ClickProxy());
        mBinding.setVm(mViewModel);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 获取底部banner图的回调
        mRequestViewModel.getShowList().observe(this, get_show_list -> {
            List<String> bannerFeedList = new ArrayList<>();
            List<String> bannerTitleList = new ArrayList<>();
            for (int i = 0; i < get_show_list.getAdvListList().size(); i++) {
                bannerFeedList.add(get_show_list.getAdvListList().get(i).getAdvCode()
                        + "," + get_show_list.getAdvListList().get(i).getAdvId());
                bannerTitleList.add("");
            }
            mViewModel.bannerFeedList.addAll(bannerFeedList);
            mViewModel.bannerTitleList.addAll(bannerTitleList);
        });

        // 回调头部个人信息的
        mRequestViewModel.getMember().observe(this, member -> {
            mBinding.tvGoodsName.setText(member.getMerchantFull());
            switch (member.getMerchantLevel()) {
                case "1":
                    mBinding.ivLevel.setBackgroundResource(R.mipmap.icon_level_putong);
                    break;
                case "2":
                    mBinding.ivLevel.setBackgroundResource(R.mipmap.icon_level_huangjin);
                    break;
                case "3":
                    mBinding.ivLevel.setBackgroundResource(R.mipmap.icon_leve_baijin);
                    break;
                case "4":
                    mBinding.ivLevel.setBackgroundResource(R.mipmap.icon_level_zhuanshi);
                    break;
            }
            if (member.getMerchantType().equals("1")) {
                mBinding.ivShopType.setBackgroundResource(R.mipmap.icon_wei);
            } else {
                mBinding.ivShopType.setBackgroundResource(R.mipmap.icon_biao);

            }
        });
        // 回调每月收益
        mRequestViewModel.getHomePage().observe(this, home_page -> {
            mViewModel.amount_today.set("¥ " + home_page.getAmountToday());
            mViewModel.limit_toady.set("今日额度 ¥ " + home_page.getLimitToady());
            mViewModel.amount_total.set(home_page.getNumToday() + "笔");
            mViewModel.limit_total.set("今日可收款笔数: " + home_page.getCanNumToday() + "笔");
//            mViewModel.num_total.set(home_page.getNumTotal() + "笔");
            int todayPe = (int) ((Float.parseFloat(home_page.getAmountToday()) / Float.parseFloat(home_page.getLimitToady())) * 100);
            int TotalPe = (int) ((Float.parseFloat(home_page.getNumToday()) / Float.parseFloat(home_page.getCanNumToday())) * 100);
            mBinding.circularProgressView.setProgress(todayPe, todayPe * 15);
            mBinding.circularProgressView2.setProgress(TotalPe, TotalPe * 15);
        });
        // 回调消息 (第一条消息标题和内容的拼接)
        mRequestViewModel.getSystem_logs().observe(this, systemLogLists -> {
            hideProgress();
            if (systemLogLists.size() > 0) {
                mViewModel.pm_text.set(systemLogLists.get(0).getPushTitle() + " " + systemLogLists.get(0).getPushMessage());
            }
        });
        // 获取banner
        mRequestViewModel.getbanner();
        // 获取头部个人信息
        mRequestViewModel.getMemberInfo();
        // 获取每月收益
        mRequestViewModel.getHomePageInfo();
        // 获取系统消息
        mRequestViewModel.system_log(1);

        NetworkManager.INSTANCE.post(Apis.sys_switch, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                MemberOuterClass.sys_switch systeLog = MemberOuterClass.sys_switch.parseFrom(bytes);
                mViewModel.sys_switch.set(systeLog.getScanSwitch().equals("1"));
                mViewModel.sys_ji_fen.set(systeLog.getPointSwitch().equals("1"));
                mViewModel.agency_switch.set(systeLog.getAgencySwitch().equals("1"));
                Log.e("1111", systeLog.getWxSwitch());
                mViewModel.wx_switch.set(systeLog.getWxSwitch().equals("1"));

                mViewModel.ll_switch.set(systeLog.getWxSwitch().equals("1") || systeLog.getPointSwitch().equals("1"));

                mViewModel.point_html_url = systeLog.getPointHtmlUrl();
            }

            @Override
            public void onError(int code, String errorMessage) {
            }
        });

        mSharedViewModel.isHomeLoad.observe(this, isLoad -> {
            if (isLoad) {
                mRequestViewModel.getHomePageInfo();
            }
        });


        NetworkManager.INSTANCE.post(Apis.get_wallet, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                Settle.get_wallet getWallet = Settle.get_wallet.parseFrom(bytes);
                mViewModel.wallet_d0.set("￥" + intChange2Str(getWallet.getWalletD0()) );
                mViewModel.wallet_t1.set("￥" +intChange2Str(getWallet.getWalletT1()) );
                mViewModel.wallet_total.set("￥" + intChange2Str(getWallet.getWalletTotal()) );
                mViewModel.wallet_temp.set("￥" + intChange2Str(getWallet.getWalletTemp()) );

                double  walletDo = Double.parseDouble(getWallet.getWalletD0());
                double  walletT1 = Double.parseDouble(getWallet.getWalletT1());
                double  walletTemp = Double.parseDouble(getWallet.getWalletTemp());
                double  walletWei = walletDo +  walletT1 + walletTemp;
                String  walletWeiString = String.valueOf(walletWei);
                mViewModel.wallet_weichu.set("￥" + intChange2Str(walletWeiString) );


            }

            @Override
            public void onError(int code, String errorMessage) {
            }
        });

    }


    private String intChange2Str(String numberString) {
        double number = Double.parseDouble(numberString);
        String str = "";
        if (number < 10000) {
            BigDecimal b = new BigDecimal(number);
            double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();//2.转换后的数字四舍五入保留小数点后一位;
            str = f1+"";
        } else if (10000 <= number && number < 100000000) {
            double d = (double) number;
            double num = d / 10000;//1.将数字转换成以万为单位的数字
            BigDecimal b = new BigDecimal(num);
            double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();//2.转换后的数字四舍五入保留小数点后一位;
            str = f1 + "万";
        }else {
            double d = (double) number;
            double num = d / 100000000;//1.将数字转换成以万为单位的数字
            BigDecimal b = new BigDecimal(num);
            double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();//2.转换后的数字四舍五入保留小数点后一位;
            str = f1 + "亿";
        }
        return str;
    }


    public class ClickProxy {
        public void GoToNext(View view) {
            int id = view.getId();
            if (id == R.id.ll_zhan_dan) {
                nav().navigate(R.id.action_mainRootFragment_to_zhanDanFragment);
            } else if (id == R.id.ll_jie_suan_ka) {
                nav().navigate(R.id.action_mainRootFragment_to_jieSuanKaFragment);
            } else if (id == R.id.ll_qr_code) {
//                nav().navigate(R.id.action_mainRootFragment_to_qrFragment);
                WebViewActivity.startActivity(mActivity, Apis.serverHead + mViewModel.point_html_url);
            } else if (id == R.id.ll_she_bei) {
                nav().navigate(R.id.action_mainRootFragment_to_sheBeiFragment);
            } else if (id == R.id.tv_up) {
                WebViewActivity.startActivity(mActivity, WebApis.merchantsLevel);
            } else if (id == R.id.tv_system_message) {
                nav().navigate(R.id.action_mainRootFragment_to_messageFragment);
            } else if (id == R.id.ll_ka_bao) {
                WebViewActivity.startActivity(mActivity, WebApis.cardBag);
            } else if (id == R.id.tv_up_level) {
                nav().navigate(R.id.action_mainRootFragment_to_upAgentFragment);
            } else if (id == R.id.ll_bao_bei) {
                WebViewActivity.startActivity(mActivity, WebApis.reported);
            } else if (id == R.id.ll_zhang_hu || id == R.id.rv_gai_lan) {
                WebViewActivity.startActivity(mActivity, WebApis.account);
            }
        }

    }
}


